<?php 
//@ no sirve
class EnumBehavior extends ModelBehavior{
    var $__settings = array();
	    
    function setup(&$Model, $settings = array()){
        
    	if (!isset($this->__settings[$Model->alias])){
			$this->__settings[$Model->alias] = $settings;
		}
          	
    }
    
    function afterFind(&$model, $results){
 		if(!isset($results[0][$model->alias])){
 			return $results;
 		}
    	 		
 		$fields=array_keys($results[0][$model->alias]);
 		$enum_fields=array_intersect($fields, $this->__settings[$model->alias]['fields']);
 		
 		if(!empty($enum_fields)){
 			$db =& ConnectionManager::getDataSource($model->useDbConfig);
			$tableName = $db->fullTableName($model, false);
         	
 			foreach ( $results AS $key => $r ) {
                foreach ($enum_fields as $f){
                	$enum='';
                	if($r[$model->alias][$f]>0){
                		$enum=$model->query('SELECT enum FROM enums WHERE `id` = \''.$r[$model->alias][$f].'\' AND `table`= \''.$tableName.'\' AND `field`=\''.$f.'\' LIMIT 1');
                		$enum=$enum[0]['enums']['enum'];
                	}
                	$results[$key][$model->alias][$f]=$enum;
                }
            }
 		}

 		return $results;
    }
            
    function beforeFind(&$model){
		if(isset($model->conditions)&& !empty($model->conditions)) $model->conditions=$this->rewriteConditions($model,$model->conditions,$stackConditions=array());
	}
	
	function rewriteConditions($conditions,$stackConditions=array()){
		if(empty($conditions)) return $stackConditions;
		pr($conditions);
		exit;
		//$stackConditions[]=$this->rewriteConditions(array_pop($conditions),$conditions, $stackConditions)
		
	}
    
    
    function find($algo,$ar){
		$db =& ConnectionManager::getDataSource($this->useDbConfig);
		$tableName = $db->fullTableName($this, false);
        $cacheKey = $model->alias . '_' . $field . '_enum_options';
    $options = Cache::read($cacheKey);

    if (!$options) {
      $sql = "SHOW COLUMNS FROM `{$model->useTable}` LIKE '{$field}'";
      $enumData = $model->query($sql);

      $options = false;
      if (!empty($enumData)) {
        $patterns = array('enum(', ')', '\'');
        $enumData = r($patterns, '', $enumData[0]['COLUMNS']['Type']);
        $options = explode(',', $enumData);
      } 	
    }}
}